(function () {
    $(".show-download-image").click(function(e) {
        e.preventDefault();
        $(".splash-intro").addClass("invisible");
        $(".splash-wait-anim").addClass("invisible");
        $(".splash-download-image").removeClass("invisible");

        $("#show-download-image").removeClass('shake-animated');

        $('#pic-name-holder').html((new Date).getTime());

    });

    $(".show-filter").click(function() {

        // this slows down animation
        $(".switch").toggleClass("on");

        if(currentOptionShown == 0){
            $(".layout-list").transition({
                    'margin-left' : '-70px'
                },
                500,
                'cubic-bezier(0,0.9,0.3,1)'
            );
            currentOptionShown = 1;
        }
        else
        {
            $(".layout-list").transition({
                    'margin-left' : '-320px'
                },
                500,
                'cubic-bezier(0,0.9,0.3,1)'
            );
            currentOptionShown = 0;
        }
    });


    $(".show-info").click(function() {
        if(currentOptionShown == 0){
            $(".layout-list").transition({
                    'margin-left' : '-570px'
                },
                500,
                'cubic-bezier(0,0.9,0.3,1)'
            );
            currentOptionShown = 1;
        }
        else
        {
            $(".layout-list").transition({
                    'margin-left' : '-320px'
                },
                500,
                'cubic-bezier(0,0.9,0.3,1)'
            );
            currentOptionShown = 0;
        }
    });



    var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
    if (size == 'widescreen') {
        alert("computed widescreen");
        // go nuts
    }

    // Listen to all CamanJS instances


    Caman.Event.listen("processStart", function (job) {

        //console.log("Start:", job.name);
        photo.hide();
        $(".splash-wait-anim").toggleClass("invisible");
        $('#show-download-image').removeClass('shake-animated');
        $('#menu').removeClass('shake-animated');


    });

    Caman.Event.listen("processComplete", function (job) {
        //console.log("Finished:", job.name);
        $(".splash-wait-anim").toggleClass("invisible");
        $(".splash-download-image").addClass("invisible");
        $('#show-download-image').addClass('shake-animated');
        photo.show();

    });


    function requestFullScreen(el) {
        // Supports most browsers and their versions.
        var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;

        if (requestMethod) { // Native full screen.
            requestMethod.call(el);
        } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    }

    var elem = document.body; // Make the body go full screen.
    requestFullScreen(elem);



    var	maxWidth = 320,
        maxHeight = 428;
    photo = $('#photo'),
        bokeh_wait = $('.splash-wait-anim');

    //bokeh_wait = $('#circle-container');
    originalCanvas = null;
    filters = $('#filters li a'),
        filterContainer = $('#filterContainer'),
        imgHeight = 0,
        imgWidth = 0,
        firstOpen = true,
        imgname = "",
        currentOptionShown = 0;

    //imagePresenter = document.querySelector("#image_presenter");

    //bokeh_wait.hide();


    /*
     WebActivities:

     configure
     costcontrol/balance
     costcontrol/data_usage
     costcontrol/telephony
     dial
     new (type: "websms/sms", "webcontacts/contact") (add-contact, compose-mail?)
     open
     pick (type: "image/png" etc)
     record (capture?)
     save-bookmark
     share
     test
     view (type: "url" etc. "text/html"?)
     */

    // WebActivities


    //bokeh_wait.addClass('invisible');



    $('#pick-image').addClass('shake-animated');



    var pickImage = document.querySelector("#pick-image");
    var pickImageSec = document.querySelector("#pick-image-sec");




        pickImage.onclick = function(){
            pickImageHandler();
        }
        pickImageSec.onclick = function(){
            pickImageHandler();
        }
        

        function pickImageHandler() {


            var pick = new MozActivity({
                name: "pick",
                data: {
                    type: ["image/png", "image/jpg", "image/jpeg"]
                }
            });

            pick.onsuccess = function () {

                $('#pick-image').removeClass('shake-animated');
                $('#menu').addClass('shake-animated');

                $(".splash-intro").addClass("invisible");
                $(".splash-wait-anim").addClass("invisible");
                $(".splash-download-image").addClass("invisible");

                var src = window.URL.createObjectURL(this.result.blob);

                var img = $('<img>').appendTo(photo),
                    imgWidth, newWidth,
                    imgHeight, newHeight,
                    ratioh, ratiow, ratio;

                // Remove canvas elements left on the page
                // from previous image drag/drops.

                photo.find('canvas').remove();
                //filters.removeClass('active');

                // When the image is loaded successfully,
                // we can find out its width/height:

                img.load(function() {

                    imgWidth  = this.width;
                    imgHeight = this.height;

                    // Calculate the new image dimensions, so they fit
                    // inside the maxWidth x maxHeight bounding box

                    if (imgWidth >= maxWidth || imgHeight >= maxHeight) {

                        // The image is too large,
                        // resize it to fit a 500x500 square!

                        ratioh = imgHeight / maxHeight;
                        ratiow = imgWidth / maxWidth;

                        ratio = (ratioh > ratiow)?ratioh:ratiow;

                        newHeight = imgHeight / ratio;
                        newWidth = imgWidth / ratio;


                    } else {
                        newHeight = imgHeight;
                        newWidth = imgWidth;
                    }

                    // Create the original canvas.

                    originalCanvas = $('<canvas>').appendTo(photo);
                    var originalContext = originalCanvas[0].getContext('2d');

                    // Set the attributes for centering the canvas

                    originalCanvas.attr({
                        width: newWidth,
                        height: newHeight
                    });

                    // Draw the dropped image to the canvas
                    // with the new dimensions
                    originalContext.drawImage(this, 0, 0, newWidth, newHeight);

                    // We don't need this any more
                    img.remove();

                    //filterContainer.fadeIn();

                    // Trigger the default "normal" filter
                    //filters.first().click();
                });

                // Set the src of the img, which will
                // trigger the load event when done:

                img.attr('src', src);

            };

            pick.onerror = function () {


                $(".splash-intro").removeClass("invisible");
                //$(".splash-wait-anim").toggleClass("invisible");


                alert("Can't view the image!");
            };
        }


    filters.click(function(e){

	        $(".switch").toggleClass("on");
	
	
        e.preventDefault();


        $(".layout-list").animate({
            'margin-left' : '-320px'
        },{
            duration : 150,
            easing : "swing"
        });



        currentOptionShown = 0;


        var f = $(this);

        if(f.is('.active')){
            // Apply filters only once
            return false;
        }

        filters.removeClass('active');
        f.addClass('active');

        // Clone the canvas
        var clone = originalCanvas.clone();

        // Clone the image stored in the canvas as well



        clone[0].getContext('2d').drawImage(originalCanvas[0],0,0);


        // Add the clone to the page and trigger
        // the Caman library on it



        photo.find('canvas').remove().end().append(clone);

        var effect = $.trim(f[0].id);

        Caman(clone[0], function () {

            // If such an effect exists, use it:

            if( effect in this){
                this[effect]();
                this.render();

                // Show the download button
                showDownload(clone[0]);


            }
            else{
                //hideDownload();
            }
        });

    });


    var downloadImage = $('a.download-image');

    function showDownload(canvas){


        downloadImage.off('click').click(function(){




            imgname = $('#pic-name-holder').html();

            if(imgname.length == 0) return;

            /**
             * http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata/5100158
             *
             *
             */
            function dataURItoBlob(dataURI, callback) {
                // convert base64 to raw binary data held in a string
                // doesn't handle URLEncoded DataURIs

                var byteString;
                if (dataURI.split(',')[0].indexOf('base64') >= 0) {
                    byteString = atob(dataURI.split(',')[1]);
                } else {
                    byteString = unescape(dataURI.split(',')[1]);
                }

                // separate out the mime component
                var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                // write the bytes of the string to an ArrayBuffer
                var ab = new ArrayBuffer(byteString.length);
                var ia = new Uint8Array(ab);
                for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                }

                // write the ArrayBuffer to a blob, and you're done
                var BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder;
                var bb = new BlobBuilder();
                bb.append(ab);
                return bb.getBlob(mimeString);
            }

            function getAsJPEGBlob(canvas) {
                if(canvas.mozGetAsFile) {
                    return canvas.mozGetAsFile("foo.jpg", "image/jpeg");
                } else {
                    var data = canvas.toDataURL('image/jpeg', 0.7);
                    var blob = dataURItoBlob(data);
                    return blob;
                }
            }

            // When the download link is clicked, get the
            // DataURL of the image and set it as href:

            var url = canvas.toDataURL("image/png;base64;");

            var pictures = navigator.getDeviceStorage("pictures");

            var file = getAsJPEGBlob(canvas);


            var request = pictures.addNamed(file, imgname + ".png");

            request.onsuccess = function () {
                alert('Picture saved successfully :)');
                $('.splash-download-image').addClass('invisible');

            }

            // An error typically occur if a file with the same name already exist
            request.onerror = function () {
                alert("I'm sorry, I'm unable to save your picture :(");
            }

            //downloadImage.attr('href', url);

        }).fadeIn();

    }

}





    /*
     Loosely based on Firefox-OS-Boilerplate-App: https://github.com/robnyman/Firefox-OS-Boilerplate-App
     */



    )();